﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ModelBinder.Extension.AspNetCore.FromSmartBody;
using VueShopApi.Common;
using VueShopApi.Common.Extensions;
using VueShopApi.Entities;

namespace VueShopApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UsersController : AuthorizeController
    {
        private readonly ILogger<UsersController> _logger;
        private readonly IFreeSql _context;

        public UsersController(ILogger<UsersController> logger, IFreeSql context)
        {
            _logger = logger;
            _context = context;
        }

        /// <summary>
        /// 获取所有管理员
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pagenum"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetAllManagers(string query, int pagenum = 1, int pagesize = 5)
        {
            var users = await _context.Select<SpManager, SpRole>()
                .LeftJoin((mgr, role) => mgr.RoleId == role.RoleId)
                .WhereIf(!string.IsNullOrWhiteSpace(query), (mgr, role) => mgr.MgName.Contains(query))
                .Count(out var total)
                .Page(pagenum, pagesize)
                .ToListAsync((mgr, role) => new
                {
                    id = mgr.MgId,
                    role_name = role.RoleName,
                    username = mgr.MgName,
                    create_time = mgr.MgTime,
                    mobile = mgr.MgMobile,
                    email = mgr.MgEmail,
                    mg_state = mgr.MgState == 1
                });

            return ServerResponse.Yes(new { total, pagenum, pagesize, users });
        }

        /// <summary>
        /// 通过管理员 ID 获取管理员信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetManager([FromRoute] int id)
        {
            var manager = await _context.Select<SpManager>(id).ToOneAsync();
            if (manager == null)
                return ServerResponse.No("该管理员不存在");

            return ServerResponse.Yes(new
            {
                id = manager.MgId,
                rid = manager.RoleId,
                username = manager.MgName,
                mobile = manager.MgMobile,
                email = manager.MgEmail
            });
        }

        /// <summary>
        /// 创建管理员
        /// </summary>
        /// <param name="email"></param>
        /// <param name="mobile"></param>
        /// <param name="password"></param>
        /// <param name="username"></param>
        /// <param name="rid"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateManager([FromSmartBody] string email,[FromSmartBody] string mobile,[FromSmartBody] string password,[FromSmartBody] string username,[FromSmartBody] int rid = -1)
        {
            if (string.IsNullOrEmpty(username))
                return ServerResponse.BadRequest("用户名不能为空");

            if (string.IsNullOrEmpty(password))
                return ServerResponse.BadRequest("密码不能为空");

            var isExists = await _context.Select<SpManager>().Where(m => m.MgName == username).AnyAsync();
            if (isExists)
                return ServerResponse.BadRequest("用户名已存在");
            var manager = new SpManager()
            {
                MgName = username,
                MgPwd = BCrypt.Net.BCrypt.HashPassword(password),
                MgMobile = mobile,
                MgEmail = email,
                MgTime = (int)DateTime.Now.ToTimeStamp(),
                RoleId = rid
            };
            manager.MgId = (int)await _context.Insert<SpManager>(manager).ExecuteIdentityAsync();

            return ServerResponse.Yes(new
            {
                id = manager.MgId,
                username = manager.MgName,
                mobile = manager.MgMobile,
                email = manager.MgEmail,
                role_id = manager.RoleId,
                create_time = manager.MgTime
            });
        }

        /// <summary>
        /// 更新管理员信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="email"></param>
        /// <param name="mobile"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateManager([FromRoute] int id,[FromSmartBody] string email,[FromSmartBody] string mobile)
        {
            var manages = await _context.Update<SpManager>(id).SetDto(new { MgMobile = mobile, MgEmail = email }).ExecuteAffrowsAsync();
            if (manages > 0)
            {
                var manager = await _context.Select<SpManager>(id).ToOneAsync();
                return ServerResponse.Yes(new
                {
                    id = manager.MgId,
                    username = manager.MgName,
                    mobile = manager.MgMobile,
                    email = manager.MgEmail,
                    role_id = manager.RoleId,
                    create_time = manager.MgTime
                });
            }

            return ServerResponse.No("管理员ID不存在");
        }

        /// <summary>
        ///   通过管理员 ID 进行删除操作
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteManager([FromRoute] int id)
        {
            if (id == 500)
                return ServerResponse.BadRequest("不允许删除admin账户");

            await _context.Delete<SpManager>(id).ExecuteAffrowsAsync();
            return ServerResponse.Yes();
        }

        /// <summary>
        /// 为管理员设置角色
        /// </summary>
        /// <param name="id"></param>
        /// <param name="rid"></param>
        /// <returns></returns>
        [HttpPut("{id}/Role")]
        public async Task<IActionResult> SetManagerRole([FromRoute] int id, [FromSmartBody] int rid)
        {
            var manages = await _context.Update<SpManager>(id).SetDto(new { RoleId = rid }).ExecuteAffrowsAsync();
            if (manages > 0)
            {
                var manager = await _context.Select<SpManager>(id).ToOneAsync();
                return ServerResponse.Yes(new
                {
                    id = manager.MgId,
                    username = manager.MgName,
                    mobile = manager.MgMobile,
                    email = manager.MgEmail,
                    role_id = manager.RoleId,
                    create_time = manager.MgTime
                });
            }

            return ServerResponse.No("管理员ID不存在");
        }

        /// <summary>
        /// 更改管理员状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        [HttpPut("{id}/State/{state}")]
        public async Task<IActionResult> UpdateManagerState([FromRoute] int id, [FromRoute] bool state)
        {
            var manages = await _context.Update<SpManager>(id).SetDto(new { MgState = state ? 1: 0 }).ExecuteAffrowsAsync();
            if (manages > 0)
            {
                var manager = await _context.Select<SpManager>(id).ToOneAsync();
                return ServerResponse.Yes(new
                {
                    id = manager.MgId,
                    username = manager.MgName,
                    mobile = manager.MgMobile,
                    email = manager.MgEmail,
                    role_id = manager.RoleId,
                    create_time = manager.MgTime
                });
            }

            return ServerResponse.No("管理员ID不存在");
        }

    }
}
